import { PathGeometry, PathPointList } from './three.path.module.js';
import * as THREE from 'three';
import { Reflector } from './Reflector.js'; // 镜面

export default class PathRoad {
  constructor(_model = {}, _viewer, _laneData) {
    // this.position = _model.position;
    this.yAxis = _model?.position?.y || 0;

    this.viewer = _viewer;
    this.scene = _viewer.scene;
    // this.callback = _callback;
    this.laneData = _laneData;
  }

  createLane() {
    let yAxis = this.yAxis;
    const { x, y, width, height, tunnelNumber } = this.laneData;
    let halfWidth = width / 2;
    let halfHeight = height / 2;
    const innerPosition = new THREE.Vector3(x + halfWidth, 1.1, y + halfHeight);
    const outerPosition = new THREE.Vector3(x + halfWidth, 1, y + halfHeight);
    const textPosition = new THREE.Vector3(x + halfWidth, 1.2, y + halfHeight);

    const canvas = document.createElement('canvas');
    canvas.width = 128;
    canvas.height = 128;

    const context = canvas.getContext('2d');
    context.beginPath();
    context.font = '30px Arial';
    context.fillStyle = 'black'; // 设置颜色
    context.textAlign = 'center';
    context.fillText(tunnelNumber, canvas.width / 2, canvas.height / 2);
    context.fill();

    const shadowTexture = new THREE.CanvasTexture(canvas);
    const canvasText = new THREE.PlaneGeometry(width, width);
    const materialText = new THREE.MeshPhongMaterial({
      map: shadowTexture,
      toneMapped: false,
      depthWrite: false,
      transparent: true,
      opacity: 0.9,
      color: 0xff0000,
      side: THREE.FrontSide
    });
    const textMesh = new THREE.Mesh(canvasText, materialText);
    textMesh.rotation.x = -Math.PI / 2;
    textMesh.position.y = yAxis + 0.3;
    textMesh.position.z = 3;

    let planePath = new THREE.PlaneGeometry(width, height);

    let laneMesh = new Reflector(planePath, {
      clipBias: 1,
      textureWidth: width * window.devicePixelRatio,
      textureHeight: height * window.devicePixelRatio,
      color: 0x4caf50 // 绿色ss
    });
    laneMesh.rotation.x = -Math.PI / 2;
    laneMesh.position.y = yAxis + 0.2;

    let planePathBorder = new THREE.PlaneGeometry(width + 0.2, height + 0.2);
    const borderMaterial = new THREE.MeshBasicMaterial({
      color: 'rgb(221, 165, 15)'
    });

    let laneOuterMesh = new THREE.Mesh(planePathBorder, borderMaterial);
    laneOuterMesh.rotation.x = -Math.PI / 2;
    laneMesh.position.y = yAxis + 0.1;

    let laneGroup = new THREE.Group();
    laneGroup.add(textMesh);
    laneGroup.add(laneMesh);
    laneGroup.add(laneOuterMesh);

    this.scene.add(laneGroup);

    return laneGroup;
  }
}
